package com.yn.iotxiao.dotnet;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

/**
 * .netcore id4 的token认证
 */
public class HttpContext {

    private static final String jwkSetUri = System.getenv("IDENTITYSERVER_URI") + "/.well-known/openid-configuration/jwks";



    public static DotNetUser getUserFromToken(String token) {

        Jwt jwt = jwtDecoder(token);
        DotNetUser userInfo = new DotNetUser();
        userInfo.setUid(jwt.getClaim("uid"));
        userInfo.setName(jwt.getClaim("name"));
        userInfo.setType(jwt.getClaim("type"));
        userInfo.setSchId(jwt.getClaim("schId"));
        userInfo.setNavId(jwt.getClaim("navId"));
        userInfo.setNavName(jwt.getClaim("navName"));
        return userInfo;
    }

    private static Jwt jwtDecoder(String token) {
        token = token.replace("Bearer ", "");
        var decoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
                .jwtProcessorCustomizer(customizer -> {
                    customizer.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("at+jwt")));
                })
                .build();

        return decoder.decode(token);
    }
}
